package com.nmp.common;

import com.nmp.controller.IndexController;
import com.nmp.model.SessionModel;
import com.nmp.model.UserModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;

/**
 *
 * @author vuln2
 */
public class CommonUtil {
    private static final Logger logger = Logger.getLogger(IndexController.class);
    public static final byte HEADER_HTML = 0;
    public static final byte HEADER_JS = 1;
    
    private static final String STATIC_URL = ConfigFactory.getStrParam("static", "static_url");
    private static final String AVATAR_PATH = ConfigFactory.getStrParam("upload", "upload_avatar");

    public static String getHeader() throws Exception {
        TemplateDataDictionary headerVariable = TemplateDictionary.create();
        Template template = RenderModel.getCTemplate("block_header");
        return template.renderToString(headerVariable);
    }

    public static String getFooter() throws Exception {
        TemplateDataDictionary footerVariable = TemplateDictionary.create();
        Template template = RenderModel.getCTemplate("block_footer");
        return template.renderToString(footerVariable);
    }

    public static String getMenu(HttpServletRequest req) throws Exception {
        TemplateDataDictionary menuVariable = TemplateDictionary.create();
        SessionModel sessionModel = SessionModel.getInstance();
        String user_login_id = sessionModel.getUserLogin(req);
        if(!user_login_id.equalsIgnoreCase("")) {
            UserModel userModel = UserModel.getInstance();
            UserData userData;
            if(user_login_id.startsWith("fb") || user_login_id.startsWith("gg")) {
                userData = userModel.getUserByAppUserId(user_login_id);
            } else {
                userData = userModel.getUserById(user_login_id);
            }
            
            if(userData != null) {
                menuVariable.setVariable("LOGIN_NAME", userData.getName());
                menuVariable.setVariable("LOGIN_AVATAR", STATIC_URL + AVATAR_PATH + "/" + userData.getAvatar());
                menuVariable.showSection("LOGED_IN_SECTION");
            } else {
                menuVariable.showSection("NOT_LOGED_IN_SECTION");
            }
        } else {
            menuVariable.showSection("NOT_LOGED_IN_SECTION");
        }
        Template template = RenderModel.getCTemplate("block_menu");
        return template.renderToString(menuVariable);
    }

    public static String md5(String pass) {
        try {
            return DigestUtils.md5Hex(pass);
        } catch (Exception ex) {
        }
        return "";
    }

    public static String toJSON(int error, String msg) {
        Map mapdata = new HashMap();
        JSONObject ldata = new JSONObject();
        mapdata.put("err", error);
        mapdata.put("msg", msg);
        ldata.putAll(mapdata);
        return ldata.toJSONString();
    }

    public static String toJSON(int error, String msg, String data) {
        Map mapdata = new HashMap();
        JSONObject ldata = new JSONObject();
        mapdata.put("err", error);
        mapdata.put("msg", msg);
        mapdata.put("data", data);
        ldata.putAll(mapdata);
        return ldata.toJSONString();
    }

    public static String toJSON(int error, String msg, Map data) {
        Map mapdata = new HashMap();
        JSONObject ldata = new JSONObject();
        mapdata.put("err", error);
        mapdata.put("msg", msg);
        mapdata.put("data", data);
        ldata.putAll(mapdata);
        return ldata.toJSONString();
    }

    public static String toJSON(int error, String msg, List<Map> data) {
        Map mapdata = new HashMap();
        JSONObject ldata = new JSONObject();
        mapdata.put("err", error);
        mapdata.put("msg", msg);
        mapdata.put("data", data);
        ldata.putAll(mapdata);
        return ldata.toJSONString();
    }

    public static void out(String content, HttpServletResponse respon) throws IOException {
        PrintWriter out = respon.getWriter();
        out.print(content);
    }

    public static void prepareHeader(HttpServletResponse resp, byte type) {
        resp.setCharacterEncoding("utf-8");
        if (type == HEADER_HTML) {
            resp.setContentType("text/html; charset=utf-8");
        } else if (type == HEADER_JS) {
            resp.setContentType("text/javascript; charset=utf-8");
        }
        String appName = ConfigFactory.getParam("webserver", "app_name");
        resp.addHeader("Server", appName);
    }

    public static boolean checkSession(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        SessionModel sessionModel = SessionModel.getInstance();
        return !(!pathInfo.startsWith("/register") && sessionModel.getUserLogin(req).equalsIgnoreCase(""));
    }

    public static String getPageNavi(int current, int postCount, int postPerPage, String link) {
        Pattern p = Pattern.compile("-?\\d+");
        Matcher m = p.matcher(link);
        while (m.find()) {
            String tmp = m.group();
            link = link.replace("?p=" + tmp, "?")
                    .replace("&p=" + tmp, "");
        }
        if (link.lastIndexOf("?") == link.length() - 1) {
            link = link.replace("?", "");
        }

        String html = "";
        String paramDelimiter = link.contains("?") ? "&" : "?";
        if (postCount > postPerPage) {
            int totalPage = postCount / postPerPage + (postCount % postPerPage > 0 ? 1 : 0);
            int PAGEGAP = 3;
            String li = "";
            for (int i = 1; i <= totalPage; i++) {
                String pageNum;
                String url;
                if (i > 1 && i < totalPage && Math.abs(i - current) > PAGEGAP) {
                    i = i < current ? current - PAGEGAP : totalPage - 1;
                    pageNum = "...";
                    url = "#";
                } else {
                    pageNum = String.valueOf(i);
                    url = link + paramDelimiter + "p=" + i;
                }
                li += "<li class=\"" + (current == i ? "active" : "") + "\">"
                        + "<a href=\"" + url + "\">" + pageNum + "</a>"
                        + "</li>";
            }
            String firstPage = "<li class=\"" + (current == 1 ? "disabled" : "") + "\">"
                    + "<a href=\"" + link + paramDelimiter + "p=1\">&laquo;</a>"
                    + "</li>";
            String lastPage = "<li class=\"" + (current == totalPage ? "disabled" : "") + "\">"
                    + "<a href=\"" + link + paramDelimiter + "p=" + totalPage + "\">&raquo;</a>"
                    + "</li>";
            html = "<ul style=\"margin: 0;\" class=\"pagination pagination-md pull-right\">" + firstPage + li + lastPage + "</ul>";
        }
        return html;
    }

    public static BufferedImage convertPNGToJPG(BufferedImage bufferedImage) {
        BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
        newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
        return newBufferedImage;
    }

    public static boolean validateEmail(String email) {
        String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    public static boolean saveImageFile(String imageUrl, String destinationFile) {
        try {
            URL url = new URL(imageUrl);
            InputStream is = url.openStream();
            OutputStream os = new FileOutputStream(destinationFile);

            byte[] b = new byte[2048];
            int length;

            while ((length = is.read(b)) != -1) {
                os.write(b, 0, length);
            }

            is.close();
            os.close();
        } catch (Exception ex) {
            return false;
        }
        return true;
    }
}
